<!DOCTYPE html>
<script src='../resources/testharness.js'></script>
<script src='../resources/testharnessreport.js'></script>
<script src='resources/shadow-dom.js'></script>
<script src='../fullscreen/trusted-click.js'></script>

<div id='host1'>
  <template data-mode='open'>
    <slot></slot>
  </template>
  <div id='host2'>
    <template data-mode='open'>
      <div id='host3'>
        <template data-mode='open'>
          <canvas></canvas>
          <div id='host4'>
            <template data-mode='open'>
              <div></div>
            </template>
          </div>
        </template>
      </div>
      <div id='host5'>
        <template data-mode='open'>
          <div></div>
        </template>
      </div>
    </template>
  </div>
</div>

<script>
async_test((test) => {
    document.onfullscreenerror = test.unreached_func('onfullscreenerror is not expected.');

    convertTemplatesToShadowRootsWithin(host1);

    var host3 = host2.shadowRoot.querySelector('#host3');
    var host4 = host3.shadowRoot.querySelector('#host4');
    var host5 = host2.shadowRoot.querySelector('#host5');

    // All fullscreenElement should default to null.
    assert_equals(document.fullscreenElement, null);
    assert_equals(document.webkitFullscreenElement, null);
    assert_equals(document.webkitCurrentFullScreenElement, null);
    assert_equals(host1.shadowRoot.fullscreenElement, null);
    assert_equals(host2.shadowRoot.fullscreenElement, null);
    assert_equals(host3.shadowRoot.fullscreenElement, null);
    assert_equals(host4.shadowRoot.fullscreenElement, null);
    assert_equals(host5.shadowRoot.fullscreenElement, null);

    var canvas = host3.shadowRoot.querySelector('canvas');
    trusted_request(test, canvas);

    document.onfullscreenchange = test.step_func(() => {
        // Not interested in handling before or after exitFullscreen.
        if (document.fullscreenElement === null)
            return;

        assert_equals(document.fullscreenElement, host2);
        assert_equals(document.webkitFullscreenElement, host2);
        assert_equals(document.webkitCurrentFullScreenElement, host2);

        assert_equals(host1.shadowRoot.fullscreenElement, null);
        assert_equals(host2.shadowRoot.fullscreenElement, host3);
        assert_equals(host3.shadowRoot.fullscreenElement, canvas);
        assert_equals(host4.shadowRoot.fullscreenElement, null);
        assert_equals(host5.shadowRoot.fullscreenElement, null);

        document.exitFullscreen();
        test.done();
    });

}, 'Test for fullscreenElement adjustment for multiple shadow trees.');
</script>
